package com.bysj.yqsht.service.impl;


import com.bysj.yqsht.bean.Account;
import com.bysj.yqsht.bean.AccountExample;
import com.bysj.yqsht.bean.extend.AccountExtend;
import com.bysj.yqsht.dao.AccountMapper;
import com.bysj.yqsht.dao.extend.AccountExtendMapper;
import com.bysj.yqsht.service.IAccountService;
import com.bysj.yqsht.utils.CustomerException;
import com.bysj.yqsht.utils.JwtToken;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class IAccountServiceImpl implements IAccountService {
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private AccountExtendMapper accountExtendMapper;


    @Override
    public List<Account> findAll() {
        AccountExample example = new AccountExample();
        return accountMapper.selectByExample(example);

    }

    @Override
    public List<AccountExtend> findWithAll(int pageNum, int limit) {
        PageHelper.startPage(pageNum,limit);
        AccountExample example = new AccountExample();
        List<AccountExtend> list1 = accountExtendMapper.findWithAll();
        PageInfo<AccountExtend> data = new PageInfo<AccountExtend>(list1);
        List<AccountExtend> list = data.getList();
        return list;
    }

    @Override
    public List<AccountExtend> findWithAllBy(Long roleId,String name) {

        System.out.println(roleId);
        List<AccountExtend> withAllBy = accountExtendMapper.findWithAllBy(roleId,name);
        System.out.println(withAllBy);
        return withAllBy;


    }

    @Override
    public void saveOrUpdate(Account account) {
        if(account.getId() != null){
            accountMapper.updateByPrimaryKey(account);
        } else {
            List<Account> u1 = accountExtendMapper.yanzheng(account.getUsers());
                if(u1 != null){
                    throw new CustomerException("该账号已经存在");
                }
            accountMapper.insert(account);
        }

    }



    @Override
    public void deleteById(long id) {
       accountMapper.deleteByPrimaryKey(id);


    }

    @Override
    public String login(String username, String password) {
        Account account = accountExtendMapper.findByUsername(username);
        if (account == null){
            throw new CustomerException("该用户不存在");
        }
        if (!account.getPassword().equals(password)){
            throw new CustomerException("用户名或密码错误");
        }
        String token = JwtToken.getJwtToken(account.getId(),account.getUsers(),account.getRoleId());
        return token;
    }
}
